from rest_framework.viewsets import ModelViewSet
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.pagination import PageNumberPagination

from books import models
from books import serializers


class BooksViewSet(ModelViewSet):
    """
    list:           获取书籍列表
    create:         添加书籍信息
    retrieve:       查看书籍详情
    update:         更新书籍全部记录
    partial_update: 更新书籍部分记录
    delete:         删除书籍
    """
    # 认证
    authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication]

    # 权限
    permission_classes = [IsAuthenticated, ]

    # 分页
    pagination_class = PageNumberPagination

    # 搜索
    search_fields = ("isbn", "book_name", "author",)

    # 过滤
    filter_fields = ("publisher", "bookshelf")

    # 排序
    ordering_fields = ("created_at", "updated_at")

    # 模型
    queryset = models.BooksModel.objects.all()

    # 序列化器， 如果是查询接口 读取只读序列化器
    def get_serializer_class(self):
        if self.action in ["list", "retrieve"]:
            return serializers.BooksReadOnlySerializer
        return serializers.BooksSerializer


class BookshelfViewSet(ModelViewSet):
    """
    list:           获取书架列表
    create:         添加书架信息
    retrieve:       查看书架详情
    update:         更新书架全部记录
    partial_update: 更新书架部分记录
    delete:         删除书架
    """
    # 认证
    authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication]

    # 权限
    permission_classes = [IsAuthenticated, ]

    # 分页
    pagination_class = PageNumberPagination

    # 搜索
    search_fields = ("shelf_name",)

    # 过滤
    filter_fields = ("shelf_location",)

    # 排序
    ordering_fields = ("capacity", "created_at", "updated_at")

    # 模型
    queryset = models.BookshelfModel.objects.all()

    # 序列化器
    serializer_class = serializers.BookshelfSerializer


class PublisherViewSet(ModelViewSet):
    """
    list:           获取出版社列表
    create:         添加出版社信息
    retrieve:       查看出版社详情
    update:         更新出版社全部记录
    partial_update: 更新出版社部分记录
    delete:         删除出版社
    """
    # 认证
    authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication]

    # 权限
    permission_classes = [IsAuthenticated, ]

    # 分页
    pagination_class = PageNumberPagination

    # 搜索
    search_fields = ("publisher_name", "contact_person", "contact_phone", "address", "email", "website")

    # 过滤
    filter_fields = ()

    # 排序
    ordering_fields = ("created_at", "updated_at")

    # 模型
    queryset = models.PublisherModel.objects.all()

    # 序列化器
    serializer_class = serializers.PublisherSerializer
